<!-- subpkg_consult/payment/index.vue -->
<script lang="ts" setup>
import {
  getPatientConsultOrderPreAPI,
  postPatientConsultOrderAPI,
  postPatientConsultPayAPI,
} from '@/api/consult'
import { getPatientInfoAPI } from '@/api/user'
import { useConsultStore } from '@/store/consult'
import type { GetPatientConsultOrderPreRes } from '@/types/consult'
import type { CustomPaymentInstance } from '@/types/GlobalComponents'
import type { GetPatientInfoRes } from '@/types/user'
import { ref } from 'vue'

// 1. 获取问诊信息
const store = useConsultStore()

const list = ref<GetPatientConsultOrderPreRes>()
const getConsultOrderPre = async () => {
  const res = await getPatientConsultOrderPreAPI({
    type: store.query.type,
    illnessType: store.query.illnessType,
  })
  list.value = res
}
getConsultOrderPre()

// 2. 获取患者信息
const patientInfo = ref<GetPatientInfoRes>()
const getPatientInfo = async () => {
  const res = await getPatientInfoAPI(store.patientID)
  patientInfo.value = res
}
getPatientInfo()

// 3. 保存问诊订单
const orderId = ref('')
const handlePay = async () => {
  if (orderId.value) {
    uni.showToast({
      title: '不能重复创建订单',
      icon: 'error',
    })
    return
  }
  console.log(store.illnessInfo.pictures, 'store.illnessInfo.pictures')

  const res = await postPatientConsultOrderAPI({
    type: +store.query.type,
    illnessType: +store.query.illnessType,
    patientId: store.patientID,
    depId: store.query.depId,
    illnessDesc: store.illnessInfo.illnessDesc,
    illnessTime: store.illnessInfo.illnessTime,
    consultFlag: store.illnessInfo.consultFlag,
    pictures: store.illnessInfo.pictures?.map((item) => ({ id: item.id, url: item.url })),
  })
  orderId.value = res.id
  store.clearOrder()
  customPaymentRef.value?.open?.()
}

// 4. 支付弹窗
const customPaymentRef = ref<CustomPaymentInstance>()

// 5. 确认退出
const onPaymentClose = async () => {
  const res = await uni.showModal({
    title: '关闭支付',
    content: '取消支付将无法获得医生回复，医生接诊名额有限，是否确认关闭？',
    cancelText: '仍要关闭',
    cancelColor: '#848484',
    confirmText: '继续支付',
    confirmColor: '#16C2A3',
  })
  if (res.cancel) {
    customPaymentRef.value?.close?.()
  }
}

// 6. 支付方式改变
const onPaymentChange = (index: number) => {
  console.log('支付方式改变', index)
}

// 7. 确认支付
const onPaymentConfirm = async (index: number) => {
  console.log('确认支付', index)
  if (index === 0) {
    uni.showToast({
      title: '暂不支持微信支付',
      icon: 'none',
    })
    // #ifdef MP-WEIXIN
    // 本质还是发送网络请求，获取后端返回的参数
    // 调用微信支付的 API (SDK方法)
    // wx.requestPayment(传入后端返回的支付参数)
    // #endif
  } else if (index === 1) {
    // 根据当前网址,获取基地址
    const baseUrl = window.location.origin
    const payCallback = `${baseUrl}/#/subpkg_consult/room/room`
    const res = await postPatientConsultPayAPI({
      orderId: orderId.value,
      paymentMethod: '1',
      payCallback,
    })
    console.log('支付结果', res)
    location.href = res.payUrl
  }
}
</script>

<template>
  <scroll-view>
    <view class="payment-page">
      <uni-section
        title-font-size="32rpx"
        title-color="#121826"
        padding="30rpx"
        :title="`${
          store.query.type === '1' ? '问医生' : store.query.type === '2' ? '极速问诊' : '开药问诊'
        } ${list?.payment ?? ''}元`"
      >
        <uni-list :border="false">
          <uni-list-item
            :title="
              store.query.type === '2'
                ? '极速问诊'
                : store.query.type === '3'
                ? '开药问诊'
                : '问医生'
            "
            note="自动分配医生"
            thumb="/static/uploads/doctor-avatar.jpg"
            thumb-size="lg"
          />
          <uni-list-item
            title="优惠券"
            show-arrow
            :right-text="`-¥${list?.couponDeduction ?? ''}`"
          />
          <uni-list-item title="积分抵扣">
            <template #footer>
              <view class="uni-list-text-red">-¥{{ list?.pointDeduction ?? '' }}</view>
            </template>
          </uni-list-item>
          <uni-list-item title="实付款">
            <template #footer>
              <view class="uni-list-text-red">¥{{ list?.actualPayment ?? '' }}</view>
            </template>
          </uni-list-item>
        </uni-list>
      </uni-section>

      <view class="dividing-line"></view>

      <uni-section title-font-size="32rpx" title-color="#121826" padding="30rpx" title="患者资料">
        <uni-list :border="false">
          <uni-list-item title="患者信息">
            <template #footer>
              <view class="uni-list-text-gray">
                {{ patientInfo?.name }} | {{ patientInfo?.genderValue }} | {{ patientInfo?.age }}岁
              </view>
            </template>
          </uni-list-item>
          <uni-list-item border title="病情描述" :note="store.illnessInfo.illnessDesc" />
        </uni-list>
      </uni-section>

      <!-- <view class="payment-agreement">
        <radio color="#20c6b2" value="1" />
        我已同意<text style="color: #20c6b2">支付协议</text>
      </view> -->
    </view>
    <!-- 下一步操作 -->
    <view class="next-step">
      <view class="total-amount">
        合计: <text class="number">¥{{ list?.payment ?? '' }}</text>
      </view>
      <button class="uni-button" @click="handlePay">立即支付</button>
    </view>

    <!-- 支付弹层 -->
    <custom-payment
      ref="customPaymentRef"
      :amount="list?.payment ?? 0"
      :order-id="orderId"
      @close="onPaymentClose"
      @change="onPaymentChange"
      @confirm="onPaymentConfirm"
    />
  </scroll-view>
</template>

<style lang="scss">
@import './index.scss';
</style>
